// hooks/useAuth.js
import { useEffect, useState } from 'react';

const useAuth = () => {
    const [authState, setAuthState] = useState({
        isAuthenticated: false,
        userPermissions: [],
        loading: true
    });

    useEffect(() => {
        const fetchUserFromLocalStorage = () => {
            try {
                const userInfoString = localStorage.getItem('userInfo');
                if (userInfoString) {
                    const userInfo = JSON.parse(userInfoString);
                    const token = userInfo.token;
                    if (token) {
                        setAuthState({
                            isAuthenticated: true,
                            userPermissions: userInfo.permissions || [], // 确保权限字段存在
                            loading: false
                        });
                    } else {
                        setAuthState({
                            isAuthenticated: false,
                            userPermissions: [],
                            loading: false
                        });
                    }
                } else {
                    setAuthState({
                        isAuthenticated: false,
                        userPermissions: [],
                        loading: false
                    });
                }
            } catch (error) {
                console.error('Failed to fetch user data from localStorage:', error);
                setAuthState({
                    isAuthenticated: false,
                    userPermissions: [],
                    loading: false
                });
            }
        };

        fetchUserFromLocalStorage();
    }, []);

    return authState;
};

export default useAuth;